package site.tiangao.async.kt

import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController


@SpringBootApplication
@RestController
class DemoApplication {

    @Value("\${test.url}")
    lateinit var testUrl: String

    @GetMapping("/v")
    fun v() = "kotlin"

    @GetMapping("/mid")
    fun test() = runBlocking {
        val start = System.currentTimeMillis()
        val redis = async { getRes("redis", start) }
        val dal = async { getRes("dal", start) }
        val image = async { getRes("image", start) }
        val sss = async { getRes("sss", start) }
        "${dal.await()} ${redis.await()} ${image.await()} ${sss.await()}"
    }

    suspend fun getRes(s: String, start: Long): String {
        println("${Thread.currentThread().name} $s >> ${System.currentTimeMillis() - start}")
        val url = "$testUrl/$s"
        val future = httpClient.prepareGet(url).execute()
        while (!future.isDone) {
            delay(1)
        }
        println("${Thread.currentThread().name} $s << ${System.currentTimeMillis() - start}")
        return future.get().responseBody
    }
}

fun main(args: Array<String>) {
    runApplication<DemoApplication>(*args)
}